// pages/index/subPages/user/user.js
import store from '../../../../modules/store'
import tool from '../../../../modules/tool'
import config from '../../../../config'

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    imagePrefix: config.imagePrefix,
    userData: {},
    adminOptions: [
      {
        icon: '设置',
        title: '管理员后台',
        callBack() {

          const setting_banner = async (reloadAdminMenuPage) => {
            if (store.getItem('banner') === undefined) {
              tool.handleShowToast('无法获取轮播图，请重启小程序')
              return
            }

            tool.controlSettingsPage('轮播图', (reloadBannerPage) => {
              let re = store.getItem('banner')
              let settings = []
              const handleUpdateBannerToServer = async () => {
                let re = await tool.requestData('/setting/update', {
                  key: 'banner',
                  value: store.getItem('banner')
                })
                if (re.status) {
                  tool.handleShowToast('成功', 'success')
                  reloadBannerPage()
                } else {
                  tool.handleShowToast(re.content)
                }
              }
              const handleUpdateBannerText = async (index, text) => {
                let re = store.getItem('banner')
                re[index].text = text
                store.setItem('banner', re)
                await handleUpdateBannerToServer()
              }
              const handleUpdateBannerFileName = async (index, fileName) => {
                let re = store.getItem('banner')
                re[index].fileName = fileName
                store.setItem('banner', re)
                await handleUpdateBannerToServer()
              }
              const handleUpdateBannerIndex = async (index, toIndex) => {
                let re = store.getItem('banner')
                let t = tool.dcJSON(re[index])
                re[index] = re[toIndex]
                re[toIndex] = t
                store.setItem('banner', re)
                await handleUpdateBannerToServer()
              }
              const handleDeleteBanner = async (index) => {
                let re = store.getItem('banner')
                re = [...re.slice(0, index), ...re.slice(index + 1)]
                store.setItem('banner', re)
                await handleUpdateBannerToServer()
              }
              const handleAddBanner = async (image, text) => {
                let re = store.getItem('banner')
                re.push({
                  fileName: image,
                  text
                })
                store.setItem('banner', re)
                await handleUpdateBannerToServer()
              }

              for (let i = 0; i < re.length; i++) {
                settings.push({
                  title: `轮播图${i + 1}`,
                  list: [
                    {
                      title: '预览',
                      right: {
                        type: 'image',
                        src: re[i].fileName
                      },
                      callBack: () => {
                        wx.previewImage({
                          urls: [config.imagePrefix + re[i].fileName],
                        })
                      }
                    },
                    {
                      title: '文本',
                      right: {
                        type: 'text',
                        value: re[i].text,
                      },
                      callBack: async () => {
                        tool.controlInput(`编辑轮播图${i + 1}的文本`, '', 'singleText', re[i].text, async (value, done) => {
                          await handleUpdateBannerText(i, value)
                          wx.navigateBack()
                        }, (value) => {
                          if (typeof (value) === 'string' && value.length > 16) {
                            throw new Error('文本的字数不能大于16')
                          }
                        })
                      }
                    },
                    {
                      title: '操作',
                      callBack: () => {
                        let il = ['更改图片']
                        if (i) {
                          il.push('上移')
                        }
                        if (i != re.length - 1) {
                          il.push('下移')
                        }
                        il.push('删除')
                        wx.showActionSheet({
                          itemList: il,
                          success: async (tapIndex) => {
                            tapIndex = tapIndex.tapIndex
                            switch (il[tapIndex]) {
                              case '更改图片':
                                let re = await tool.chooseImage(1)
                                re = await tool.compressImage(re[0])
                                let uploadRes = await tool.uploadFileToServer(re)
                                if (JSON.parse(uploadRes).status) {
                                  await tool.requestData('/file/delete', {
                                    fileName: re[i].fileName,
                                  })
                                  await handleUpdateBannerFileName(i, JSON.parse(uploadRes).data)
                                } else {
                                  tool.handleShowToast('上传失败', 'error')
                                }
                                break;
                              case '上移':
                                await handleUpdateBannerIndex(i, i - 1)
                                break;
                              case '下移':
                                await handleUpdateBannerIndex(i, i + 1)
                                break;
                              case '删除':
                                tool.handleShowModel(`是否删除第${i + 1}个轮播图？`, true, async () => {
                                  await handleDeleteBanner(i)
                                })
                                break;
                            }
                          }
                        })
                      }
                    }
                  ]
                })
              }

              settings.push({
                list: [
                  {
                    title: '添加',
                    icon: 'add',
                    callBack: async () => {
                      try {
                        let image = await tool.chooseImage(1)
                        image = await tool.compressImage(image[0])
                        tool.controlInput('请输入轮播图文字', '', 'singleText', '', async (value, done) => {
                          done()
                          let uploadImage = await tool.uploadFileToServer(image)
                          uploadImage = JSON.parse(uploadImage)
                          if (uploadImage.status) {
                            await handleAddBanner(uploadImage.data, value)
                          } else {
                            tool.handleShowToast('上传失败', 'error')
                          }
                        }, (value) => {
                          if (typeof (value) === 'string' && value.length > 16) {
                            throw new Error('轮播图文字不能长于16')
                          }
                        })
                      } catch (error) {
                        console.log(error)
                      }

                    }
                  }
                ]
              })
              return settings
            })
          }

          const setting_notification = async (reloadAdminMenuPage) => {
            if (store.getItem('notification') === undefined) {
              tool.handleShowToast('无法获取通知，请重启小程序')
              return
            }

            async function handleSaveNotification() {
              let t = store.getItem('notification')
              t.sort((a, b) => {
                if (new Date(a.time) > new Date(b.time)) return -1
                if (new Date(a.time) < new Date(b.time)) return 1
                return 0
              })
              store.setItem('notification', t)
              let re = await tool.requestData('/setting/update', {
                key: 'notification',
                value: store.getItem('notification')
              })
              if (re.status) {
                re = await tool.requestData('/setting/home', {}, 'get')
                if (re.status) {
                  store.setItem('notification', re.data.notification)
                  tool.handleShowToast('成功', 'success')
                } else {
                  tool.handleShowToast('已保存但未更新', 'error')
                }
              } else {
                tool.handleShowToast(re.content, 'error')
              }
            }

            async function handleEditText(index, text) {
              let t = store.getItem('notification')
              t[index].text = text
              store.setItem('notification', t)
              await handleSaveNotification()
            }

            async function handleEditWarning(index, value) {
              let t = store.getItem('notification')
              t[index].warning = value ? true : undefined
              store.setItem('notification', t)
              await handleSaveNotification()
            }

            async function handleUpdateTime(index) {
              let t = store.getItem('notification')
              let re = await tool.requestData('/getServerTime', {}, 'get')
              if (re.status) {
                t[index].time = re.data
                store.setItem('notification', t)
                await handleSaveNotification()
              }
            }

            async function handleDelete(index) {
              let t = store.getItem('notification')
              t = [...t.slice(0, index), ...t.slice(index + 1)]
              store.setItem('notification', t)
              await handleSaveNotification()
            }

            async function handleAdd(text) {
              let t = store.getItem('notification')
              t.push({
                text: text,
                time: await tool.getServerTime()
              })
              await handleSaveNotification()
            }

            tool.controlSettingsPage('通知', (reloadNotificationPage) => {
              let notification = store.getItem('notification')
              let settings = []
              for (let i = 0; i < notification.length; i++) {
                settings.push({
                  title: `通知${i + 1}`,
                  list: [
                    {
                      title: '内容',
                      right: {
                        type: 'text',
                        value: notification[i].text
                      },
                      callBack: async () => {
                        tool.controlInput(`编辑通知的内容`, '', 'multipleText', notification[i].text, async (value, done) => {
                          await handleEditText(i, value)
                          done()
                          reloadNotificationPage()
                        }, (value) => {
                          if (value.length > 256) {
                            throw new Error('通知长度不能超过256')
                          }
                        })
                      }
                    },
                    {
                      title: '颜色',
                      right: {
                        type: 'text',
                        value: notification[i].warning ? '红色' : '默认'
                      },
                      callBack: () => {
                        wx.showActionSheet({
                          itemList: ['默认', '红色'],
                          success: async (e) => {
                            e = e.tapIndex
                            await handleEditWarning(i, e)
                            reloadNotificationPage()
                          }
                        })
                      }
                    },
                    {
                      title: '操作',
                      callBack: () => {
                        let list = ['更新时间', '删除']
                        wx.showActionSheet({
                          itemList: list,
                          success: async (e) => {
                            e = e.tapIndex
                            switch (list[e]) {
                              case '更新时间':
                                await handleUpdateTime(i)
                                reloadNotificationPage()
                                break;
                              case '删除':
                                tool.handleShowModel('是否删除此通知？', true, async () => {
                                  await handleDelete(i)
                                  reloadNotificationPage()
                                })
                                break;
                            }
                          }
                        })
                      }
                    }
                  ]
                })
              }

              settings.push({
                list: [
                  {
                    title: '添加',
                    icon: 'add',
                    callBack: async () => {
                      tool.controlInput('请输入通知内容', '', 'multipleText', '', async (value, done) => {
                        await handleAdd(value)
                        done()
                        reloadNotificationPage()
                      }, (value) => {
                        if (!value) throw new Error('请输入通知内容')
                        if (value.length > 256) {
                          throw new Error('通知长度不能超过256')
                        }
                      })
                    }
                  }
                ]
              })

              return settings
            })
          }

          const setting_order = async (reloadAdminMenuPage) => {
            tool.controlAdminManage('查找商品', 'searchProduct')
          }

          const setting_order_add = async (reloadAdminMenuPage) => {
            tool.handleShowProductEditorPage()
          }

          const setting_event = async (reloadAdminMenuPage) => {
            tool.controlAdminManage('查找活动', 'searchActivity')
          }

          const setting_event_add = async (reloadAdminMenuPage) => {
            tool.handleShowActivityEditorPage()
          }

          const setting_user = async (search = '', reloadAdminMenuPage) => {
            let config = {
              page: 1,
              size: 10,
              total: 0
            }

            tool.controlSettingsPage('用户列表', async (reloadUserListPage) => {
              let re = await tool.requestData('/user/search', {
                search,
                ...config
              }, 'get')
              if (re.status) {
                re = re.data
                config.total = re.searchTotal
              } else {
                tool.handleShowToast(re.content, 'error')
              }

              let settings = [

              ]
              for (let i = 0; i < re.data.length; i++) {
                settings.push({
                  title: re.data[i].username,
                  right: {
                    type: 'image',
                    src: re.data[i].avatar
                  },
                  callBack: async () => {

                    tool.handleShowUserInfoPage(re.data[i].openId)

                  }
                })
              }

              settings = [
                {
                  list: settings,
                },
                {
                  title: `${config.page}/${tool.getPageByPageSize(config.size, config.total)}`,
                  list: await tool.execFunc(async () => {
                    let re = []
                    if (config.page > 1) {
                      re.push({
                        title: '第一页',
                        callBack: async () => {
                          config.page = 1
                          reloadUserListPage()
                        }
                      })
                      re.push({
                        title: '上一页',
                        callBack: async () => {
                          config.page--
                          reloadUserListPage()
                        }
                      })
                    }
                    if (config.page < tool.getPageByPageSize(config.size, config.total)) {
                      re.push({
                        title: '下一页',
                        callBack: async () => {
                          config.page++
                          reloadUserListPage()
                        }
                      })
                      re.push({
                        title: '最后一页',
                        callBack: async () => {
                          config.page = tool.getPageByPageSize(config.size, config.total)
                          reloadUserListPage()
                        }
                      })
                    }

                    return re
                  })
                }
              ]


              return settings
            })
          }

          tool.controlSettingsPage('管理员后台', (reloadAdminMenuPage) => {
            return [
              {
                title: '首页',
                list: [
                  {
                    title: '轮播图',
                    async callBack() {
                      setting_banner(reloadAdminMenuPage)
                    }
                  },
                  {
                    title: '通知',
                    async callBack() {
                      setting_notification(reloadAdminMenuPage)
                    }
                  }
                ]
              },
              {
                title: '点餐',
                list: [
                  {
                    title: '查找',
                    async callBack() {
                      setting_order(reloadAdminMenuPage)
                    }
                  },
                  {
                    title: '添加',
                    async callBack() {
                      setting_order_add(reloadAdminMenuPage)
                    }
                  }
                ]
              },
              {
                title: '活动',
                list: [
                  {
                    title: '查找',
                    async callBack() {
                      setting_event(reloadAdminMenuPage)
                    }
                  },
                  {
                    title: '添加',
                    async callBack() {
                      setting_event_add(reloadAdminMenuPage)
                    }
                  }
                ]
              },
              {
                title: '用户',
                list: [
                  {
                    title: '全部',
                    async callBack() {
                      setting_user('', reloadAdminMenuPage)
                    }
                  },
                  {
                    title: '搜索',
                    async callBack() {
                      tool.controlInput('搜索用户', '根据用户名或手机号搜索', 'singleText', '', async (value, done) => {
                        setting_user(value, reloadAdminMenuPage)
                      })
                    }
                  },
                  {
                    title: '用户注册后赠送一张免费优惠券',
                    right: {
                      type: 'switch',
                      value: store.getItem('newUserCoupon')
                    },
                    callBack: async (e, a) => {
                      await tool.flow(async () => {
                        let re = await tool.requestData('/setting/update', {
                          key: 'newUserCoupon',
                          value: a
                        })
                        if (re.status) {
                          store.setItem('newUserCoupon', !store.getItem('newUserCoupon'))
                          reloadAdminMenuPage()
                        } else {
                          throw re.content
                        }
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    }
                  },
                ]
              },
              {
                title: '订单',
                list: [
                  {
                    title: '全部',
                    callBack: async () => {
                      tool.showOrdersSettingsPage(5)
                    }
                  },
                  {
                    title: '分类',
                    callBack: async () => {
                      tool.showOrdersSettingsPage()
                    }
                  },
                  {
                    title: '搜索',
                    callBack: async () => {
                      let form = {
                        username: '',
                        phone: '',
                        startTime: '',
                        endTime: '',
                        orderNo: '',
                        address: '',
                        itemTitle: '',
                        page: 1,
                        size: 5,
                        total: 0
                      }
                      tool.controlSettingsPage('搜索订单', async (reloadSearchOrderFormPage, SOFPageToTop) => {
                        let sett = []


                        const getDisplay = (key = '') => {
                          console.log(form)
                          if (form[key] == '') return '不限'
                          return form[key]
                        }

                        const formItems = [
                          {
                            title: '用户名',
                            key: 'username',
                            type: 'singleText'
                          },
                          {
                            title: '手机号',
                            key: 'phone',
                            type: 'singleText'
                          },
                          {
                            title: '创建时间 - 范围开始',
                            key: 'startTime',
                            type: 'dateTime'
                          },
                          {
                            title: '创建时间 - 范围结束',
                            key: 'endTime',
                            type: 'dateTime'
                          },
                          {
                            title: '订单号',
                            key: 'orderNo',
                            type: 'singleText'
                          },
                          {
                            title: '地址',
                            key: 'address',
                            type: 'singleText'
                          },
                          {
                            title: '商品/活动名称',
                            key: 'itemTitle',
                            type: 'singleText'
                          },
                        ]

                        for (let i = 0; i < formItems.length; i++) {
                          let c = formItems[i]
                          console.log(c.key, getDisplay(c.key))
                          sett.push({
                            title: c.title,
                            right: {
                              type: 'text',
                              value: getDisplay(c.key)
                            },
                            callBack: async () => {
                              wx.showActionSheet({
                                itemList: ['清空', '输入'],
                                success: async (e) => {
                                  e = e.tapIndex
                                  if (e === 0) {
                                    form[c.key] = ''
                                    reloadSearchOrderFormPage()
                                  }
                                  if (e === 1) {
                                    tool.controlInput(c.title, '', c.type, form[c.key], (value, done) => {
                                      form[c.key] = value
                                      console.log(form)
                                      reloadSearchOrderFormPage()
                                      done()
                                    })
                                  }
                                }
                              })
                            }
                          })
                        }

                        sett.push({
                          title: '每页显示个数',
                          right: {
                            type: 'text',
                            value: form.size,
                          },
                          callBack: async () => {
                            tool.controlInput('每页显示个数', '', 'number', form.size, (value, done) => {
                              form.size = value
                              reloadSearchOrderFormPage()
                              done()
                            }, (value) => {
                              if (isNaN(value)) throw '每页显示个数应为正整数'
                              if (value != parseInt(value)) throw '每页显示个数应为正整数'
                              if (value < 1) throw '每页显示个数应为正整数'
                            })
                          }
                        })

                        sett = [
                          {
                            title: '表单',
                            list: sett,
                          },
                          {
                            title: '操作',
                            list: [
                              {
                                title: '搜索',
                                callBack: async () => {
                                  let re = await tool.requestData('/order/search', form)
                                  if (re.status) {
                                    if (re.data.list.length == 0) {
                                      tool.handleShowToast('无订单')
                                      return
                                    }
                                  } else {
                                    tool.handleShowToast(re.content)
                                    return
                                  }
                                  form.page = 1
                                  tool.controlSettingsPage(`订单搜索结果`, async (reloadOrderSearchResultPage, OSRPageToTop) => {
                                    console.log(form)
                                    let re = await tool.requestData('/order/search', form)
                                    if (re.status) {

                                      let total = re.data.total
                                      re.data = re.data.list
                                      form.total = total

                                      let sett2 = [
                                        {
                                          title: `共${total}个`
                                        }
                                      ]
                                      for (let i = 0; i < re.data.length; i++) {
                                        let orderNo = re.data[i].orderNo
                                        sett2.push({
                                          title: re.data[i].createdAt_read,
                                          list: [
                                            {
                                              title: '状态',
                                              right: {
                                                type: 'text',
                                                value: await tool.execFunc(async () => {
                                                  if (re.data[i].status == 0) return '待支付'
                                                  if (re.data[i].status == 1) return '正在备餐'
                                                  if (re.data[i].status == 2) return '正在备餐'
                                                  if (re.data[i].status == 3) return '正在配送'
                                                  if (re.data[i].status == 4) return '已完成'
                                                }),
                                              },
                                              disabled: true
                                            },
                                            {
                                              title: '用户名',
                                              right: {
                                                type: 'text',
                                                value: re.data[i].username,
                                              },
                                              disabled: true
                                            },
                                            {
                                              title: '手机号',
                                              right: {
                                                type: 'text',
                                                value: re.data[i].phone,
                                              },
                                              callBack: () => {
                                                wx.makePhoneCall({
                                                  phoneNumber: `${re.data[i].phone}`
                                                })
                                              }
                                            },
                                            {
                                              title: '总共支付',
                                              right: {
                                                type: 'text',
                                                value: re.data[i].price_read,
                                              },
                                              disabled: true
                                            },
                                            {
                                              title: '地址',
                                              right: {
                                                type: 'text',
                                                value: re.data[i].address,
                                              },
                                              disabled: true
                                            },
                                            {
                                              title: '取单码',
                                              right: {
                                                type: 'text',
                                                value: re.data[i].code,
                                              },
                                              disabled: true
                                            },
                                            {
                                              title: '商品列表',
                                              callBack: async () => {
                                                tool.showItemList(re.data[i].orderNo)
                                              }
                                            },
                                            {
                                              title: '修改状态',
                                              callBack: async () => {
                                                handleChangeOrderStatus(re.data[i].orderNo)
                                              }
                                            }
                                          ]
                                        })
                                      }

                                      sett2.push({
                                        title: `${form.page}/${tool.getPageByPageSize(form.size, form.total)}`,
                                        list: await tool.execFunc(async () => {
                                          let re = []
                                          if (form.page > 1) {
                                            re.push({
                                              title: '第一页',
                                              callBack: async () => {
                                                form.page = 1
                                                reloadOrderSearchResultPage()
                                                OSRPageToTop()
                                              }
                                            })
                                            re.push({
                                              title: '上一页',
                                              callBack: async () => {
                                                form.page--
                                                reloadOrderSearchResultPage()
                                                OSRPageToTop()
                                              }
                                            })
                                          }
                                          if (form.page < tool.getPageByPageSize(form.size, form.total)) {
                                            re.push({
                                              title: '下一页',
                                              callBack: async () => {
                                                form.page++
                                                reloadOrderSearchResultPage()
                                                OSRPageToTop()
                                              }
                                            })
                                            re.push({
                                              title: '最后一页',
                                              callBack: async () => {
                                                form.page = tool.getPageByPageSize(form.size, form.total)
                                                reloadOrderSearchResultPage()
                                                OSRPageToTop()
                                              }
                                            })
                                          }
                                          return re
                                        })
                                      })

                                      return sett2


                                    } else {
                                      wx.navigateBack()
                                      await tool.wait(0.3)
                                      tool.handleShowToast(re.content, 'error')
                                    }
                                  })
                                }
                              }
                            ]
                          }
                        ]

                        return sett
                      })
                    }
                  }
                ]
              },
              {
                title: '新订单',
                list: [
                  {
                    title: '此设备用于连接打印机并打印标签',
                    right: {
                      type: 'switch',
                      value: wx.getStorageSync('autoPrint') == 'true'
                    },
                    callBack: async (e, a) => {
                      wx.setStorageSync('autoPrint', `${a}`)
                    }
                  },
                  {
                    title: '新订单时震动提醒',
                    right: {
                      type: 'switch',
                      value: wx.getStorageSync('newOrderVibrate') == 'true'
                    },
                    callBack: async (e, a) => {
                      wx.setStorageSync('newOrderVibrate', `${a}`)
                    }
                  }
                ]
              },
              {
                title: '优惠券链接',
                list: [
                  {
                    title: '新建',
                    callBack: async () => {
                      const form = {
                        disabled: 0,
                        desc: '',
                        endTime: tool.formatDateTime(new Date()),
                        op: {
                          name: 'addCoupon',
                          discount: 90
                        },
                        count: 0
                      }
                      tool.controlSettingsPage('新建优惠券链接', async (refreshPage_addShareLink) => {
                        return [
                          {
                            list: [
                              {
                                title: '描述',
                                right: {
                                  type: 'text',
                                  value: form.desc ? '已输入' : '未输入'
                                },
                                callBack: () => tool.controlInput('编辑描述', '', 'multipleText', '', (value, done) => {
                                  form.desc = value
                                  done()
                                  refreshPage_addShareLink()
                                }, (value) => {
                                  if (!value) throw '输入描述'
                                })
                              },
                              {
                                title: '截止时间',
                                right: {
                                  type: 'text',
                                  value: tool.formatTimeNew(new Date(form.endTime))
                                },
                                callBack: () => tool.controlPicker('选择截止时间', '', 'dateTime', form.endTime, [], (value, done) => {
                                  form.endTime = value
                                  done()
                                  refreshPage_addShareLink()
                                }, (value) => {
                                  if (new Date(value) < new Date()) throw '截止时间不能晚于当前'
                                })
                              },
                              {
                                title: '折扣',
                                right: {
                                  type: 'text',
                                  value: form.op.discount / 10
                                },
                                callBack: () => tool.controlInput('输入折扣', '0为免费，90为9折', 'number', form.op.discount, (value, done) => {
                                  form.op.discount = value
                                  done()
                                  refreshPage_addShareLink()
                                }, (value) => {
                                  value = parseInt(value)
                                  if (value < 0 || value > 100) throw '折扣应为不超过100的自然数'
                                })
                              },
                              {
                                title: '打开次数',
                                right: {
                                  type: 'text',
                                  value: form.count ? `${form.count}次` : '不限'
                                },
                                callBack: () => tool.controlInput('输入打开次数', '0为不限', 'number', form.count, (value, done) => {
                                  form.count = value
                                  done()
                                  refreshPage_addShareLink()
                                }, (value) => {
                                  value = parseInt(value)
                                  if (value < 0) throw '应为自然数'
                                })
                              },
                            ]
                          },
                          {
                            title: '操作',
                            list: [
                              {
                                title: '确定',
                                icon: 'add',
                                callBack: async () => tool.flow(async () => {
                                  if (!form.desc) throw '输入描述'
                                  let re = await tool.requestData('/shareLink/add', Object.assign(tool.dcJSON(form), {
                                    op: JSON.stringify(form.op)
                                  }))
                                  if (re.status) {
                                    tool.handleShowToastWithMask('成功')
                                    await tool.wait(0.5)
                                    wx.navigateBack()
                                    await tool.wait(0.3)
                                    tool.handleShowShareLinkPage(re.data, form.op.discount)
                                  } else {
                                    throw re.content
                                  }
                                }, err => tool.handleShowToast(`${err}`, 'error'))
                              }
                            ]
                          }
                        ]
                      })
                    }
                  },
                  {
                    title: '全部',
                    callBack: async () => {
                      const get = async () => {
                        let re = await tool.requestData('/shareLink/getList')
                        if (re.status) {
                          return re.data
                        } else {
                          throw re.content
                        }
                      }
                      const data = {
                        list: []
                      }
                      tool.flow(async () => {
                        data.list = await get()
                        tool.controlSettingsPage('全部优惠券链接列表', async (refreshLinkList) => {
                          let re = []
                          for (let i = 0; i < data.list.length; i++) {
                            re.push({
                              title: data.list[i].desc.length > 10 ? `${data.list[i].desc.slice(0, 10)}...` : data.list[i].desc,
                              right: {
                                type: 'text',
                                value: data.list[i].op.discount ? `${data.list[i].op.discount / 10}折` : '免费'
                              },
                              callBack: () => wx.showActionSheet({
                                itemList: ['删除', '链接分享', '二维码分享'],
                                success: async (e) => {
                                  e = e.tapIndex
                                  if (e === 0) {
                                    tool.handleShowModel('删除此链接？', true, () => tool.flow(async () => {
                                      let re = await tool.requestData('/shareLink/delete', {
                                        linkId: data.list[i].id
                                      })
                                      if (re.status) {
                                        data.list = await get()
                                        refreshLinkList()
                                      } else {
                                        throw re.content
                                      }
                                    }, err => tool.handleShowToast(`${err}`, 'error')))
                                  }
                                  if (e === 1) {
                                    tool.handleShowShareLinkPage(data.list[i].id, data.list[i].op.discount)
                                  }
                                  if (e === 2) {
                                    tool.flow(async () => {
                                      let re = await tool.getQRCode(`pages/index/index?type=shareLink&id=${data.list[i].id}`)
                                      wx.previewImage({
                                        urls: [re],
                                      })
                                    }, err => tool.handleShowToast(`${err}`, 'error'))
                                  }
                                }
                              })
                            })
                          }
                          return [
                            {
                              list: re
                            }
                          ]
                        })
                      }), err => tool.handleShowToast(`${err}`, 'error')
                    }
                  }
                ]
              },
              {
                title: '其他',
                list: [
                  {
                    title: '联系方式',
                    callBack: async () => {
                      let re = await tool.requestData('/setting/get', {
                        key: 'phone'
                      }, 'get')
                      if (re.status) {
                        tool.controlInput('联系方式', '顾客可以拨打此手机号', 'singleText', re.data, async (value, done) => {
                          let re = await tool.requestData('/setting/update', {
                            key: 'phone',
                            value
                          })
                          if (re.status) {
                            tool.handleShowToast('成功')
                            await tool.wait(1)
                            done()
                          } else {
                            tool.handleShowToast(re.content, 'error')
                          }
                        }, (value) => {
                          if (value == '') {

                          } else {
                            if (value.match(/1[0-9]{10}/) == null) {
                              throw '请输入正确的手机号'
                            }
                          }
                        })
                      } else {
                        tool.handleShowToast(re.content, 'error')
                      }
                    }
                  },
                  {
                    title: '自取地址',
                    callBack: async () => {
                      let re = await tool.requestData('/setting/get', {
                        key: 'takeAddress'
                      }, 'get')
                      if (re.status) {
                        tool.controlInput('自取地址', '', 'multipleText', re.data, async (value, done) => {
                          let re = await tool.requestData('/setting/update', {
                            key: 'takeAddress',
                            value: value
                          })
                          if (re.status) {
                            tool.handleShowToast('成功')
                            await tool.wait(0.5)
                            done()
                          } else {
                            tool.handleShowToast(re.content, 'error')
                          }
                        })
                      } else {
                        tool.handleShowToast(re.content, 'error')
                      }
                    }
                  },
                  {
                    title: 'VIP设置',
                    callBack: async () => {
                      let re = await tool.requestData('/setting/get', {
                        key: 'vip'
                      }, 'get')
                      if (re.status) {

                        re = re.data
                        re.vipStatus1 = re.vipStatus % 10
                        re.vipStatus2 = parseInt(re.vipStatus / 10)

                        tool.controlSettingsPage('VIP设置', async (reloadVIPSettingsPage) => {
                          const handleUpdateSetting = async () => {
                            let t = JSON.parse(JSON.stringify(re))
                            t.vipStatus = t.vipStatus2 * 10 + t.vipStatus1
                            delete t.vipStatus1
                            delete t.vipStatus2
                            let re1 = await tool.requestData('/setting/update', {
                              key: 'vip',
                              value: t
                            })
                            if (re1.status) {
                              reloadVIPSettingsPage()
                              tool.handleShowToast('成功')
                              return true
                            } else {
                              tool.handleShowToast(re1.content, 'error')
                              return false
                            }
                          }
                          let re1 = [
                            {
                              list: [
                                {
                                  title: '免费点餐数量',
                                  right: {
                                    type: 'text',
                                    value: re.vipStatus1
                                  },
                                  callBack: async () => {
                                    tool.controlInput('免费点餐数量', '', 'number', re.vipStatus1, async (value, done) => {
                                      re.vipStatus1 = value
                                      if (await handleUpdateSetting()) {
                                        await tool.wait(0.5)
                                        done()
                                      }
                                    }, (value) => {
                                      value = parseInt(value)
                                      if (isNaN(value)) throw '应为自然数'
                                      if (value < 0) throw '应为自然数'
                                    })
                                  }
                                },
                                {
                                  title: '免费参加活动数量',
                                  right: {
                                    type: 'text',
                                    value: re.vipStatus2
                                  },
                                  callBack: async () => {
                                    tool.controlInput('免费参加活动数量', '', 'number', re.vipStatus2, async (value, done) => {
                                      re.vipStatus2 = value
                                      if (await handleUpdateSetting()) {
                                        await tool.wait(0.5)
                                        done()
                                      }
                                    }, (value) => {
                                      value = parseInt(value)
                                      if (isNaN(value)) throw '应为自然数'
                                      if (value < 0) throw '应为自然数'
                                    })
                                  }
                                },
                                {
                                  title: '价格',
                                  right: {
                                    type: 'text',
                                    value: re.price_read
                                  },
                                  callBack: async () => {
                                    tool.controlInput('VIP价格', '', 'number', re.price, async (value, done) => {
                                      re.price = value
                                      if (await handleUpdateSetting()) {
                                        await tool.wait(0.5)
                                        done()
                                      }
                                    }, (value) => {
                                      value = parseInt(value)
                                      if (isNaN(value)) throw '应为正整数'
                                      if (value < 1) throw '应为正整数'
                                    })
                                  }
                                },
                                {
                                  title: 'VIP商品剩余折扣',
                                  right: {
                                    type: 'text',
                                    value: re.proDiscount / 10
                                  },
                                  callBack: async () => {
                                    tool.controlInput('VIP商品剩余折扣', '', 'number', re.proDiscount, async (value, done) => {
                                      re.proDiscount = value
                                      if (await handleUpdateSetting()) {
                                        await tool.wait(0.5)
                                        done()
                                      }
                                    }, (value) => {
                                      value = parseInt(value)
                                      if (isNaN(value)) throw '应为不大于100的自然数'
                                      if (value < 0 || value > 100) throw '应为不大于100的自然数'
                                    })
                                  }
                                },
                                {
                                  title: '权益介绍',
                                  right: {
                                    type: 'text',
                                    value: re.intro.length
                                  },
                                  callBack: async () => {
                                    tool.controlSettingsPage('VIP权益介绍', async (reloadVIPIntroPage) => {
                                      let re1 = []
                                      for (let i = 0; i < re.intro.length; i++) {
                                        re1.push({
                                          title: re.intro[i],
                                          callBack: async () => {
                                            wx.showActionSheet({
                                              itemList: ['修改', '删除'],
                                              success: async (e) => {
                                                e = e.tapIndex
                                                if (e === 0) {
                                                  tool.controlInput(`修改第${i + 1}个介绍`, '', 'singleText', re.intro[i], async (value, done) => {
                                                    re.intro[i] = value
                                                    if (await handleUpdateSetting()) {
                                                      reloadVIPIntroPage()
                                                      await tool.wait(0.5)
                                                      done()
                                                    }
                                                  }, (value) => {
                                                    if (value.length == 0) throw '请输入内容'
                                                  })
                                                }
                                                if (e === 1) {
                                                  tool.handleShowModel('是否删除此权益介绍？', true, async () => {
                                                    re.intro = [...re.intro.slice(0, i), ...re.intro(i + 1)]
                                                    if (await handleUpdateSetting()) {
                                                      reloadVIPIntroPage()
                                                    }
                                                  })
                                                }
                                              }
                                            })
                                          }
                                        })
                                      }
                                      return [
                                        {
                                          list: re1
                                        },
                                        {
                                          title: '操作',
                                          list: [
                                            {
                                              title: '添加',
                                              icon: 'add',
                                              callBack: async () => {
                                                if (re.intro.length == 3) {
                                                  tool.handleShowToast('最多添加3个介绍', 'error')
                                                  return
                                                }
                                                tool.controlInput('添加介绍', '', 'singleText', '', async (value, done) => {
                                                  re.intro.push(value)
                                                  if (await handleUpdateSetting()) {
                                                    reloadVIPIntroPage()
                                                    await tool.wait(0.5)
                                                    done()
                                                  }
                                                }, (value) => {
                                                  if (value.length == 0) {
                                                    throw '请输入内容'
                                                  }
                                                })
                                              }
                                            }
                                          ]
                                        }
                                      ]
                                    })
                                  }
                                },
                              ]
                            }
                          ]
                          return re1
                        })

                      } else {
                        tool.handleShowToast(re.content, 'error')
                      }
                    }
                  },
                  {
                    title: '测试打印',
                    callBack: async () => {
                      wx.navigateTo({
                        url: '/pages/printTest/printTest',
                      })
                    }
                  },
                  {
                    title: '门店已关闭',
                    right: {
                      type: 'switch',
                      value: store.getItem('storeClosed')
                    },
                    callBack: async (e, a) => {
                      await tool.flow(async () => {
                        let re = await tool.requestData('/setting/update', {
                          key: 'storeClosed',
                          value: a
                        })
                        if (re.status) {
                          store.setItem('storeClosed', !store.getItem('storeClosed'))
                          reloadAdminMenuPage()
                        } else {
                          throw re.content
                        }
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    }
                  },
                ]
              },
            ]
          })
        },
      },
      {
        icon: 'link',
        title: 'WebSocket未连接',
        right: {
          type: 'image',
          src: 'linkDisconnected.png'
        },
        disabled: true
      },
      {
        icon: 'printer2',
        title: '打印机未连接',
        right: {
          type: 'image',
          src: 'linkDisconnected.png'
        },
        disabled: true
      },
      {
        title: '点餐待处理订单',
        icon: 'order',
        callBack: async () => {
          wx.navigateTo({
            url: '/pages/preToDo/preToDo',
          })
        }
      },
      {
        title: '活动参与名单',
        icon: 'navigate_main_event',
        callBack: async () => {
          tool.controlAdminManage('选择一个活动', `searchActivity2`)
        }
      }
    ],
    userOptions: [{
      icon: '编辑',
      title: '个人资料',
      callBack(ref) {
        tool.controlSettingsPage('个人资料', (refreshPage) => {
          return [
            {
              title: '头像',
              list: [
                {
                  title: '预览',
                  icon: 'navigate_main_user',
                  callBack() {
                    wx.previewImage({
                      urls: [config.imagePrefix + store.getItem('userData').avatar],
                    })
                  }
                },
                {
                  title: '修改',
                  icon: 'navigate_main_user',
                  right: {
                    type: 'chooseAvatar',
                    src: store.getItem('userData').avatar
                  },
                  disabled: true,
                  async callBack(e) {
                    let re = await tool.uploadFileToServer(e)
                    if (re.status == 0) {
                      tool.handleShowToast('头像上传失败', 'error')
                      return
                    }
                    try {
                      re = JSON.parse(re)
                    } catch (error) {

                    }
                    re = re.data
                    let re1 = await tool.requestData('/user/update/avatar', {
                      openId: store.getItem('userData').openId,
                      fileName: re
                    })
                    if (re1.status == 1) {
                      await tool.updateUserDataAndRefreshMain({
                        avatar: re
                      })
                      this.right.src = re
                      tool.handleShowToast('成功')
                      ref()
                    } else {
                      tool.handleShowToast(re1.content, 'error')
                    }
                  }
                },
              ]
            },
            {
              title: '基本信息',
              list: [
                {
                  title: '用户名',
                  icon: '用户',
                  right: {
                    type: 'text',
                    value: store.getItem('userData').username
                  },
                  async callBack(refreshGroup) {
                    let currentValue = this.right.value
                    tool.controlInput('修改用户名', '', 'singleText', currentValue, async (value, done) => {
                      let re = await tool.requestData('/user/update/info', {
                        openId: store.getItem('userData').openId,
                        username: value
                      })
                      if (re.status) {
                        this.right.value = value
                        tool.handleShowToast('成功', 'success')
                        wx.navigateBack()
                        await tool.updateUserDataAndRefreshMain({
                          username: value
                        })
                        refreshPage()
                      } else {
                        tool.handleShowToast(re.content)
                      }
                    }, (value) => {
                      if (!value) throw new Error('用户名不能为空')
                    })
                  }
                },
                {
                  title: '性别',
                  icon: '男性',
                  right: {
                    type: 'text',
                    value: store.getItem('userData').sex == 0 ? '保密' : (store.getItem('userData').sex == 1 ? '男' : '女')
                  },
                  async callBack(refreshGroup) {
                    wx.showActionSheet({
                      itemList: ['保密', '男', '女'],
                      alertText: '修改性别',
                      success: async (result) => {
                        let value = result.tapIndex
                        let re = await tool.requestData('/user/update/info', {
                          openId: store.getItem('userData').openId,
                          sex: value
                        })
                        if (re.status) {
                          this.right.value = (value == 0 ? '保密' : (value == 1 ? '男' : '女'))
                          tool.handleShowToast('成功', 'success')
                          await tool.updateUserDataAndRefreshMain({
                            sex: value
                          })
                          refreshPage()
                        } else {
                          tool.handleShowToast(re.content)
                        }
                      },
                      fail: (res) => { },
                      complete: (res) => { },
                    })
                  }
                },
                {
                  title: '联系电话',
                  icon: '联系电话',
                  right: {
                    type: 'text',
                    value: store.getItem('userData').phone
                  },
                  async callBack(refreshGroup) {
                    let currentValue = this.right.value
                    tool.controlInput('修改联系电话', '', 'singleText', currentValue, async (value, done) => {
                      let re = await tool.requestData('/user/update/info', {
                        openId: store.getItem('userData').openId,
                        phone: value
                      })
                      if (re.status) {
                        this.right.value = value
                        tool.handleShowToast('成功', 'success')
                        wx.navigateBack()
                        await tool.updateUserDataAndRefreshMain({
                          phone: value
                        })
                        refreshPage()
                      } else {
                        tool.handleShowToast(re.content)
                      }
                    }, (value) => {
                      if (!tool.validatePhoneNumber(value)) {
                        throw new Error('请输入正确的电话号码')
                      }
                    })
                  }
                },
                {
                  title: '生日',
                  icon: '生日',
                  right: {
                    type: 'text',
                    value: store.getItem('userData').birthday
                  },
                  async callBack(refreshGroup) {
                    let currentValue = this.right.value
                    tool.controlInput('修改生日', '', 'date', currentValue, async (value, done) => {
                      let re = await tool.requestData('/user/update/info', {
                        openId: store.getItem('userData').openId,
                        birthday: value
                      })
                      if (re.status) {
                        this.right.value = value
                        tool.handleShowToast('成功', 'success')
                        wx.navigateBack()
                        await tool.updateUserDataAndRefreshMain({
                          birthday: value
                        })
                        refreshPage()
                      } else {
                        tool.handleShowToast(re.content)
                      }
                    }, (value) => {
                      if (new Date(value) > new Date()) {
                        throw new Error('生日不能比现在晚')
                      }
                    })
                  }
                },
              ]
            },
            {
              list: [
                {
                  title: '注册时间',
                  icon: '时间',
                  disabled: true,
                  right: {
                    type: 'text',
                    value: tool.formatTimeNew(new Date(store.getItem('userData').createdAt))
                  }
                },
              ]
            }
          ]
        }
        )
      }
    },
    {
      icon: '地区',
      title: '收货地址',
      callBack: async () => {
        tool.handleSetAddress()
      }
    }
    ],
    paidMemberOptions: [],
    balanceOptions: [

    ]
  },

  /**
   * 组件的方法列表
   */
  methods: {

  },

  async attached() {
    if (tool.isLogined() == false) {
      tool.handleNotLogin()
      store.setItem('mainCurrentPageIndex', 0)
      return
    }
    //更新ws状态信息
    const changeWSToConnected = () => {
      let t = this.data.adminOptions
      t[1].right.src = 'linkConnected.png'
      t[1].title = 'WebSocket已连接'
      this.setData({
        adminOptions: t
      })
    }
    if (tool.webSocket.isConnected) {
      changeWSToConnected()
    }
    tool.webSocket.onConnected(changeWSToConnected)
    tool.webSocket.onClosed(() => {
      let t = this.data.adminOptions
      t[1].right.src = 'linkDisconnected.png'
      t[1].title = 'WebSocket正在重连'
      this.setData({
        adminOptions: t
      })

    })

    //更新打印机状态
    {
      store.onChange('printerStatusText', () => {
        let t = this.data.adminOptions
        t[2].title = (store.getItem('printerStatusText')) ? (store.getItem('printerStatusText')) : '打印机未连接'
        this.setData({
          adminOptions: t
        })
      })
      store.onChange('printerStatus', () => {
        let t = this.data.adminOptions
        if (store.getItem('printerStatus')) {
          t[2].right.src = 'linkConnected.png'
        } else {
          t[2].right.src = 'linkDisconnected.png'
        }
        this.setData({
          adminOptions: t
        })
      })
    }

    tool.setPageData(this)
    console.log(new Date(store.getItem('userData').vipEndTime))
    this.setData({
      paidMemberOptions: [
        {
          title: "余额",
          icon: 'balance',
          right: {
            type: 'text',
            value: '正在获取'
          },
          callBack: async () => {
            wx.showActionSheet({
              itemList: ['充值'],
              success: async (e) => {
                e = e.tapIndex
                if (e === 0) {
                  tool.controlInput('充值', '请输入充值金额，单位：元', 'number', '', async (value, done) => {
                    tool.handleShowModel(`是否向余额中充值${parseInt(value * 100) / 100}元？`, true, async () => {
                      tool.pay(value * 100, '余额充值')
                    })
                  }, (value) => {
                    value *= 100
                    value = parseInt(value)
                    if (isNaN(value)) throw '充值金额应为数字'
                    if (value < 1) {
                      throw '充值金额应为正数'
                    }
                  })
                }
              }
            })
          }
        },
        {
          title: '扫一扫',
          icon: 'barcode_black',
          callBack: async () => {
            tool.handleScan()
          }
        },
        {
          title: '我的订单',
          icon: 'order',
          callBack: async () => {
            tool.showMyOrderPage()
          }
        },
        {
          title: this.data.isVIP ? `年卡会员` : '普通会员',
          icon: this.data.isVIP ? `paidMember` : 'paidMember-not',
          right: this.data.isVIP ? (
            {
              type: 'text',
              value: `于${tool.formatDateTime(new Date(store.getItem('userData').vipEndTime))}到期`
            }
          ) : undefined,
          callBack: async () => {
            wx.navigateTo({
              url: '/pages/vip/vip',
            })
          }
        },
        {
          title: '购物车',
          icon: '购物车',
          callBack: async () => {
            tool.handleShowCart()
          }
        },
        {
          title: '我的优惠券',
          icon: 'coupon',
          callBack: async () => {
            tool.handleShowSelectCouponPage()
          }
        },
      ]
    })

    //更新用户信息
    {
      let re = await tool.requestData('/user/info', {
        code: await tool.getLoginCode()
      })
      if (re.status) {
        store.setItem('userData', re.data)
        let t = this.data.paidMemberOptions
        t[0].right.value = re.data.balance / 100
        this.setData({
          paidMemberOptions: t
        })
      }
    }
    this.setData({
      show: true
    })
  }
})